package org.client.iot.util;

import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;

public class StringUtils {

    public static int randomNum(int min,int max){
        return min + (int)(Math.random() * (max-min+1));
    }

    public static String strOrderByDesc(String source){
        StringBuilder sb = new StringBuilder();
        for (int i = (source.length()/2) - 1; i >= 0; i--) {
            sb.append(source.substring(i * 2,i * 2 + 2 ));
        }
        return sb.toString();
    }

    public static List<Integer> toRRIList(String rri){
        List<Integer> rriList = new ArrayList<>();
        if(StrUtil.isNotEmpty(rri)) {
            for (int i = 0; i < rri.length(); i++) {
                int index = i * 4;
                if (index >= rri.length()) {
                    break;
                }
                String sub = rri.substring(i * 4, i * 4 + 4);
                String resStr = sub.substring(2, 4) + sub.substring(0, 2);

                int hex = Integer.parseInt(resStr, 16);
                rriList.add(hex);
            }
        }
        return rriList;
    }
    /**
     * 十六进制字符串转换成字节数组
     *
     * @param hexstr
     * @return
     */
    public static byte[] hexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }
    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
//            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }
    /**
     * 16进制char转换成整型
     *
     * @param c
     * @return
     */
    public static int parse(char c) {
        if (c >= 'a') {
            return (c - 'a' + 10) & 0x0f;
        }
        if (c >= 'A') {
            return (c - 'A' + 10) & 0x0f;
        }
        return (c - '0') & 0x0f;
    }
    public static Integer hexToInt(String hex){
        int num = 0;
        try {
            num = Integer.parseInt(hex, 16);
        } catch (NumberFormatException e) {
            Log.d("ble-ring", "setTotalNum: 转换失败，"+e.getCause());
        }
        return num;
    }

    private static int getRandNumber(int min, int max) {
        return (int) (min + (Math.random() * (max - min)));
    }

    public static long bytes2LongBy4(byte[] byteNum) {
        long num = ByteBuffer.wrap(byteNum)
                .order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL;
        return num;
    }
}

